import React from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    FlatList,
    TouchableOpacity,
    ScrollView,
    TouchableWithoutFeedback,
    RefreshControl,
    Platform
} from 'react-native';
var Dimensions = require('Dimensions');
var { width } = Dimensions.get('window');
import Loading from '../../../common/Loading'
import NavigatorBar from '../../../common/NavigationBar';
import BottomBarLimit from '../../../common/BottomBarLimit'
import { listUserComment } from '../../../api/my'
import {setSpText,setHW} from '../../../component/ScreenUtil'
const Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

import BaseBridge from '../../../common/Native/BaseBridge';

const cacheData = {
    total: 0,
    items: [],
    nextPage: 1
}
export default class Reply extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            dataList: [],
            isRefreshing: false,
            moreData: true,
            isLoading: false
        }
    }
    componentDidMount() {
        global.log('componentDidMount')
        this._listUserComment();//评论列表
    }
    _listUserComment() {
        let json = {
            USER_ID: global.ECourseConstant.userInfo.uuid,
            ROWS: 8,
            PAGE: cacheData.nextPage
        }
        this.setState({
            isLoading: true
        })
        listUserComment(json).then(res => {
            global.log(res, '评论列表-----------------------------------')
            cacheData.items = this.state.dataList.concat(res.LIST);
            cacheData.total = res.PAGINATION.TOTAL;
            var data = [...cacheData.items];
            this.setState({
                loading: false,
                dataList: data,
                isLoading: false
            })
        }).catch((res) => {
            this.setState({ loading: false })
        })
    }
    hasMoreList() {
        if (this.state.dataList.length >= cacheData.total && cacheData.total > 0) {
            this.setState({
                moreData: false
            })
            return false
        }
        return true
    }
    componentWillUnmount() {
        cacheData = {
            items: [],
            nextPage: 1,
            total: 0
        }
        this.setState({
            dataList: [],
            isLoading: false,
            moreData: false
        })
    }
    _onRefresh() {
        cacheData = {
            items: [],
            nextPage: 1,
            total: 0
        }
        this.setState({
            dataList: [],
            isLoading: false,
            moreData: false
        })
        this._listUserComment();
    }
    _onScroll(event) {
        console.log(this.state.isLoading || !this.hasMoreList(), this.state.isLoading, !this.hasMoreList(), 'loadmore')
        if (this.state.isLoading || !this.hasMoreList()) {
            return;
        }

        let y = event.nativeEvent.contentOffset.y;
        let height = event.nativeEvent.layoutMeasurement.height;
        let contentHeight = event.nativeEvent.contentSize.height;
        // 如果拖拽值超过底部50，且当前的scrollview高度大于屏幕高度，则加载更多
        const _num = contentHeight - height - y;
        // global.log('offsetY-->' + y);
        // global.log('height-->' + height);
        // global.log('contentHeight-->' + contentHeight);

        // android 实现方式
        if (Platform.OS == 'android' && (y + height >= contentHeight - 30)) {
            // console.log(121212,'contentHeight');
            this.loadMoreData();
        }
        // ios 实现方式
        else if (contentHeight > height && _num < -20) {
            this.loadMoreData()
        }

    }
    loadMoreData() {
        this.setState({
            isLoading: false
        }, () => {
            // console.log('page+++++++');
            // if (!this.state.moreData) return;
            cacheData.nextPage = cacheData.nextPage + 1;
            this._listUserComment()
        });
    }
    render() {
        return (
            <View style={styles.replayBox}>
                <NavigatorBar
                    title={'评论列表'}
                    style={styles.navigatorBar}
                    leftButton={this.renderLeftButton(require('../../../assets/imgs/back.png'))}
                />
                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh.bind(this)}
                            tintColor="#FF8A00"
                            // title="加载中..."
                            titleColor="#ddd"
                            colors={['#FF8A00']}
                            progressBackgroundColor="#ffffff"
                        />
                    }
                    onScroll={this._onScroll.bind(this)}
                    scrollEventThrottle={20}
                    showsVerticalScrollIndicator={false}
                >
                    <View style={styles.con}>
                        <FlatList
                            data={this.state.dataList}
                            showsVerticalScrollIndicator={true}
                            renderItem={({ item }) => this.renderItem(item)}
                            keyExtractor={(item, index) => index} />
                    </View>
                    {this.loadMore()}
                    {this.loading()}
                    {this.NoData()}
                </ScrollView>
                <BottomBarLimit />
            </View>
        );
    }
    renderItem(item) {
        return (
            <TouchableWithoutFeedback onPress={() => this.goToReplyDetail(item.ID)}>
                <View style={styles.item}>
                    <View style={styles.itemLeft}>
                        {this.headerIcon(item)}
                    </View>
                    <View style={styles.itemRight}>
                        <View style={styles.teacherTextWidth}>
                            <Text style={styles.teacherText} numberOfLines={3}>{this.MoreText(item.TEACHER_ID, 10)}
                                {item.TEACHER_ID ? <Text style={{ color: '#666' }}> 回复了你的评论 </Text> : null}
                                {item.COMMENT_CONTENT}
                            </Text>
                            <View style={styles.timeBox}>
                                <Image style={styles.timePic} source={require('../../../assets/imgs/timePic.png')} />
                                <Text style={styles.time}>{item.CREATE_TIME} | {this.MoreText(item.COURSE_ID, 10)}</Text>
                            </View>
                        </View>
                        {item.NUMBER !== '0' ? <View style={[styles.radius, styles.newsNumBox]}>
                            <Text style={styles.newsNum}>{item.NUMBER}</Text>
                        </View> : null}
                    </View>

                </View>
            </TouchableWithoutFeedback>
        )
    }
    // 头像
    headerIcon(item) {
        if (item.PIC && item.PIC !== 'null') {
            return (
                <Image style={styles.teacherIcon} source={{ uri: item.PIC }} />
            )
        } else {
            return (
                <Image style={styles.teacherIcon} source={require('../../../assets/imgs/default.png')} />
            )
        }
    }
    goToReplyDetail(id) {
        let that = this;
        this.props.navigation.navigate('ReplyDetail', {
            id: id,
            refreshPage: function () {
                that.setState({ dataList: [], loading: true })
                that._listUserComment();
            }
        });
    }
    // 正在加载or底部
    loadMore() {

        if (this.state.loading) {
            return (
                <View style={styles.loadMore}>
                    <Text style={styles.loadMoreText}>正在加载中...</Text>
                </View>
            )
        } else {
            return (
                <View style={styles.loadMore}>
                    <Text style={styles.loadMoreText}>{this.state.dataList.length == 0 ? '暂无评论' : (this.state.dataList.length == cacheData.total ? '已经全部加载完毕' : '')}</Text>
                </View>
            )
        }
    }
    // 加载loading
    loading() {
        if (this.state.loading) {
            return (
                <View style={{ height: height - 320 }}>
                    <Loading />
                </View>
            )
        }
    }
    // 没有数据
    NoData() {
        if (!this.state.loading && !this.state.moreData && !this.state.dataList.length) {
            return (
                // 暂无数据
                <Text style={styles.empty}></Text>
            )
        }
    }
    // 字体超出
    MoreText(text, MaxNum) {
        if (text) {
            if (text.length > MaxNum) {
                return (
                    text.substring(0, MaxNum) + '...'
                )
            } else {
                return (
                    text
                )
            }
        }
    }
    // 渲染按钮 返回按钮
    renderLeftButton(image) {
        return <TouchableOpacity
            style={{ padding: 8 }}
            onPress={() => {
                if (this.props.navigation.state.routeName == "FirstRouter") {
                    BaseBridge.backToExue();
                } else {
                    this.props.navigation.goBack();
                }
            }}>
            <Image style={{ width: 34, height: 34 }} source={image} />
        </TouchableOpacity>;
    }

}
const styles = StyleSheet.create({
  NumberRadiu:{
    position:'absolute',
    height:setHW(16),
    width:setHW(16),
    borderRadius:setHW(16),
    backgroundColor:'#FF8A00',
    right:setHW(-8),
    top:setHW(-8),
  },
  replayBox: {
    backgroundColor: '#F7F7F9'
  },
  title: {
    fontSize:setSpText(34),
    textAlign: 'center',
    color: '#333',
    fontWeight: 'bold',
    backgroundColor: '#fff',
    paddingBottom: setHW(20),
    paddingTop: setHW(20),
    marginBottom: setHW(20),
  },
  empty: {
    height:height - setHW(100),
    textAlign: 'center',
    fontSize:setSpText(26),
    lineHeight: setHW(400),
  },
  item: {
    backgroundColor: '#fff',
    padding: setHW(20),
    paddingTop:setHW(30),
    flexDirection: 'row',
    borderBottomWidth:1,
    borderBottomColor:'#ebebeb',
  },
  itemLeft: {
    width: setHW(94),
    marginRight: setHW(16),
  },
  itemRight: {
    width: width - setHW(150),
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  teacherIcon: {
    height: setHW(94),
    width: setHW(94),
  },
  teacherText: {
    color: '#333',
    lineHeight:setSpText(38),
    fontSize:setSpText(28),
  },
  con: {
    paddingTop: setHW(8),
    backgroundColor: '#fff',
    marginBottom: setHW(20),
    // paddingBottom: 10
  },
  timeBox: {
    flexDirection: 'row',
    alignItems:'center',
  },
  timePic: {
    height: setHW(32),
    width: setHW(32),
    marginRight: setHW(8),
  },
  time: {
    color: '#999999',
    fontSize:setSpText(26),
  },
  // loadMore
  loadMore: {
    flexDirection: 'row',
    justifyContent: 'center',
    height: setHW(100),
    alignItems: 'center',
  },
  loadMoreText: {
    color: '#ddd',
  }
})